package com.csweimei.rentmanagementtreasure.tenant.viewModel;

import android.app.Application;
import android.widget.TimePicker;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.view.TimePickerView;
import com.csweimei.rentmanagementtreasure.http.Repository;
import com.csweimei.rentmanagementtreasure.http.entity.BaseResult;
import com.csweimei.rentmanagementtreasure.http.entity.UserInfoEntity;
import com.csweimei.rentmanagementtreasure.utils.GlideEngine;
import com.csweimei.rentmanagementtreasure.utils.GlideHandler;
import com.csweimei.rentmanagementtreasure.utils.ValidateUtils;
import com.csweimei.rentmanagementtreasure.utils.permission.RxPermissionsUtils;
import com.csweimei.rentmanagementtreasure.utils.uploadUtils.QiNiuYunBean;
import com.csweimei.rentmanagementtreasure.utils.uploadUtils.QiNiuYunUpload;
import com.csweimei.rentmanagementtreasure.utils.uploadUtils.QiNiuYunUploadCallBack;
import com.csweimei.rentmanagementtreasure.viewModel.TitleVM;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import io.reactivex.observers.DisposableObserver;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.utils.RxUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;

public class PersonInfoVM extends TitleVM {
    public PersonInfoVM(@NonNull Application application) {
        super(application);
    }

    public ObservableField<String> headimg = new ObservableField<>();

    public ObservableField<String> name = new ObservableField<>();
    public ObservableField<String> sex = new ObservableField<>();
    public ObservableField<String> birthday = new ObservableField<>();
    public ObservableField<String> IDCard = new ObservableField<>();
    public ObservableField<String> phone = new ObservableField<>();
    public ObservableField<String> WeChat = new ObservableField<>();


    public PersonInfoVM(Application mApplication, Repository mRepository) {
        super(mApplication, mRepository);
        setTitleText("个人资料");
    }
    public UserInfoEntity userInfo = model.getUserInfo();

    @Override
    public void onCreate() {
        super.onCreate();
        headimg.set(userInfo.getData().getHeadimg());
        name.set(userInfo.getData().getName());
        sex.set(userInfo.getData().getSex());
        birthday.set(userInfo.getData().getBirthday());
        IDCard.set(userInfo.getData().getIDCard());
        WeChat.set(userInfo.getData().getWeChat());
        phone.set(userInfo.getData().getPhone());
    }

    public BindingCommand selTime=  new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            TimePickerView pvTime = new TimePickerBuilder(mActivity, (date, v) -> {
                birthday.set(new SimpleDateFormat("yyyy-MM-dd").format(date));
            })
                    .setType(new boolean[]{true, true, true, false, false, false})
                    .setLabel("年", "月", "日", "", "", null)
                    .build();
            pvTime.show();
        }
    });


    public BindingCommand selImage=  new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            RxPermissionsUtils.file(mActivity, new RxPermissionsUtils.Accept() {
                @Override
                public void accept() {
                    PictureSelector.create(mActivity)
                            .openGallery(SelectMimeType.ofImage())
                            .isDisplayCamera(false)
                            .setImageEngine(GlideEngine.createGlideEngine())
                            .setMaxSelectNum(1)
                            .setMinSelectNum(1)
                            .setImageSpanCount(4)
                            .forResult(new OnResultCallbackListener<LocalMedia>() {
                                @Override
                                public void onResult(ArrayList<LocalMedia> result) {
                                    headimg.set(result.get(0).getRealPath());
                                    getQNYToken();
                                }

                                @Override
                                public void onCancel() {

                                }
                            });
                }
            });
        }
    });

    /**
     * 获取七牛云token
     */
    private void getQNYToken() {
        model.getToken()
                .compose(RxUtils.schedulersTransformer())
                .compose(RxUtils.exceptionTransformer())
                .doOnSubscribe(this)
                .doOnSubscribe(disposable -> {})
                .subscribe(new DisposableObserver<QiNiuYunBean>() {
                    @Override
                    public void onNext(QiNiuYunBean qiniuYunBean) {
                        if (ValidateUtils.isNotEmptyObjectOrString(qiniuYunBean) &&
                                ValidateUtils.isNotEmptyString(qiniuYunBean.getToken())) {
                            uploadQNY(qiniuYunBean.getToken());
                        } else {
                            ToastUtils.showShort( "请求失败，请联系管理员");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }

    private void uploadQNY(String token) {
        String suffix = headimg.get().substring( headimg.get().lastIndexOf("."));
        String key = "works/zgb/" + System.currentTimeMillis() + suffix;
        QiNiuYunUpload.uploadFileToQny(mActivity, headimg.get(), token, key, new QiNiuYunUploadCallBack() {
            @Override
            public void onSuccess(String url) {
                headimg.set(url);
            }

            @Override
            public void onFail() {

            }

            @Override
            public void onProgress(String key, double progress) {

            }
        });

    }



    public BindingCommand save = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            postData();
        }
    });

    private void postData() {
        Map<String,String> map = new HashMap<>();
        map.put("userid",model.getLoginInfo().getData().getUser_id());
        map.put("headimg",headimg.get());
        map.put("name",name.get());
        map.put("sex",sex.get());
        map.put("birthday",birthday.get());
        map.put("IDCard",IDCard.get());
        map.put("phone",phone.get());
        map.put("WeChat",WeChat.get());
        model.edituserinfo(map)
                .compose(RxUtils.schedulersTransformer())
                .compose(RxUtils.exceptionTransformer())
                .doOnSubscribe(this)
                .subscribe(new DisposableObserver<BaseResult>() {
                    @Override
                    public void onNext(BaseResult o) {
                        if (o.issucc){
                            ToastUtils.showShort(o.msg);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });


    }
}
